<?php
/**
 * Created by PhpStorm.
 * User: silenceper
 * Date: 2016/12/14
 * Time: 下午4:16
 */

namespace common\services\outstock;


use common\entities\outstock\MyscrmOutStockOrderEntity;
use common\models\common\ApplicationInfoMappingModel;
use common\models\common\OperatorModel;
use common\models\myhtsq\DocumentModel;
use common\repositories\common\MyscrmOrganizationRepository;
use common\repositories\myhtsq\DocumentRepository;
use common\repositories\myhtsq\ErpUserRepository;
use common\repositories\outstock\OutStockAttachmentRepository;
use common\repositories\outstock\OutStockOrderRepository;
use common\repositories\outstock\OutStockProductRepository;
use common\repositories\outstock\OutStockStepRepository;
use common\services\BaseService;
use common\services\common\MyscrmAuthorizeService;
use common\services\common\MyscrmContractApplicationService;
use common\services\myhtsq\ContractService;
use common\support\StringHelper;
use Yii;
use yii\helpers\ArrayHelper;

class FlowCenterService extends BaseService
{
    private $_outStockOrderRepository;

    private $_outStockProductRepository;

    public function __construct($config = [],
                                OutStockOrderRepository $outStockOrderRepository,
                                OutStockProductRepository $outStockProductRepository)
    {
        $this->_outStockOrderRepository = $outStockOrderRepository;
        $this->_outStockProductRepository = $outStockProductRepository;
        parent::__construct($config);
    }

    /**
     * 我发起的流程
     * @param int $page
     * @param int $pageSize
     * @param string $keywords
     * @return array
     */
    public function getStartList($page = 1, $pageSize = 10, $keywords = "")
    {
        $userId = \Yii::$app->user->identity->userguid;
        //TODO: condition

        $res = $this->_outStockOrderRepository->getOrderList($page, $pageSize, MyscrmOutStockOrderEntity::FLOW_START, $userId);
        $total = $res["total"];
        $data = $this->fillExtField($res["data"], MyscrmOutStockOrderEntity::FLOW_START);
        return ["total" => $total, "data" => $data];
    }

    /**
     * 我的代办列表
     * @param int $page
     * @param int $pageSize
     * @param string $keywords
     * @return array
     */
    public function getTodoList($page = 1, $pageSize = 10, $keywords = "")
    {
        $userId = \Yii::$app->user->identity->userguid;
        //TODO: condition

        $res = $this->_outStockOrderRepository->getOrderList($page, $pageSize, MyscrmOutStockOrderEntity::FLOW_TODO, $userId);
        $total = $res["total"];
        $data = $this->fillExtField($res["data"], MyscrmOutStockOrderEntity::FLOW_TODO);

        return ["total" => $total, "data" => $data];
    }

    /**
     * 获取已办列表
     * @param int $page
     * @param int $pageSize
     * @param string $keywords
     * @return array
     */
    public function getDoneList($page = 1, $pageSize = 10, $keywords = "")
    {
        //1.从flow表中取出我审批 以及 我授权完成的用户,显示出重复
        $userId = \Yii::$app->user->identity->userguid;

        $res = $this->_outStockOrderRepository->getDoneList($page, $pageSize, $userId);
        $total = $res["total"];
        $data = $this->fillExtField($res["data"], MyscrmOutStockOrderEntity::FLOW_DONE);

        return ["total" => $total, "data" => $data];
    }

    /**
     * 填充租户信息以及交付人员信息
     * @param $data
     * @param $flowStatus 流程状态
     * @return array
     * @throws \yii\base\InvalidConfigException
     */
    private function fillExtField($data, $flowStatus)
    {
        $res = [];
        /* @var $orgSerivce MyscrmOrganizationRepository */
        $orgRepository = \Yii::createObject(MyscrmOrganizationRepository::className());

        /* @var $erpUserRepository ErpUserRepository */
        $erpUserRepository = \Yii::createObject(ErpUserRepository::className());

        /* @var $outStockStepRepository OutStockStepRepository */
        $outStockStepRepository = \Yii::createObject(OutStockStepRepository::className());

        foreach ($data as $key => $order) {
            $userInfo = $erpUserRepository->getUserInfoById($order["request_user_id"]);
            $order["request_company_name"] = "";
            $order["request_user_name"] = "";
            if (!empty($userInfo)) {
                $order["company_name"] = $userInfo["CompanyName"];
                $order["request_user_name"] = $userInfo["UserName"];
            }
            $order["org_name"] = "";
            //获取租户名称
            if (!empty($order["org_code"])) {
                $org = $orgRepository->getOrgByUniqueName($order["org_code"]);
                if (!empty($org)) {
                    $order["org_name"] = $org->FriendlyName;
                }
            }
            $flowName = "";
            if (!empty($order["company_name"])) {
                $flowName .= $order["company_name"];
            }
            if (!empty($order["request_user_name"])) {
                $flowName .= "-" . $order["request_user_name"];
            }
            $flowName .= "-出库申请";
            if (!empty($order["org_name"])) {
                $flowName .= "-" . $order["org_name"];
            }
            $flowName .= "-" . $order["order_code"];
            $order["name"] = $flowName;
            $order["current_step"] = OutStockFlowService::$currentStepMap[$order["flow_status"]];
            $order["approver"] = OutStockFlowService::$approverMap[$order["flow_status"]];

            //特殊:如果是"申请中"状态,判断当前步骤 是发往财务还是区域负责人
            if ($order["flow_status"] == OutStockFlowService::STATUS_SQZ) {
                //正常单据,不需要通过区域负责人
                if ($order['contract_status'] && $order['money_status']) {
                    $order["current_step"] = "财务复核";
                    $order["approver"] = "财务负责人";
                }
            }

            //获取交付人信息
            $order["deliver_name"] = "";
            $order["deliver_phone"] = "";
            if (!empty($order["deliver_user_id"])) {
                $userInfo = $erpUserRepository->getUserById($order["deliver_user_id"]);
                if (!empty($userInfo)) {
                    $order["deliver_name"] = $userInfo["UserName"];
                    $order["deliver_phone"] = StringHelper::getLastMobilePhone($userInfo["MobilePhone"]);
                }
            }

            //如果是发起的流程还需要一个has_step字段
            $order["has_step"] = 1;
            if ($flowStatus == MyscrmOutStockOrderEntity::FLOW_START) {
                $hasStep = $outStockStepRepository->hasStep($order["id"]);
                if (!$hasStep) {
                    $order["has_step"] = 0;
                }
            }

            $res[$key] = $order;
        }

        return $res;
    }

    /**
     * 根据order_code获取
     * @param $orderCode
     * @return array|bool
     */
    public function getAllPackages($orderCode)
    {
        if (empty($orderCode)) {
            return $this->setAndReturn(-1, "order code 必填");
        }
        //获取order
        $order = $this->_outStockOrderRepository->getDetailByCode($orderCode);
        if (empty($order)) {
            return $this->setAndReturn(-1, "没有该出库信息");
        }
        //获取应用信息并且需要转换成授权时候的id
        $products = $this->_outStockProductRepository->getProductsByOrderId($order["id"]);

        /** @var ApplicationInfoMappingModel $model */
        $model = Yii::createObject(ApplicationInfoMappingModel::className());
        $applicationList = $model->getAuthApplicationList($products);

        /* @var $authorizeService MyscrmAuthorizeService */
        $authorizeService = \Yii::createObject(MyscrmAuthorizeService::className());
        //再加上不存在的app  获取所有app
        $extraApplications = $authorizeService->getExtraApplications();

        $result = array_merge($applicationList, $extraApplications);
        ArrayHelper::multisort($result,'count',SORT_DESC);

        return $result;
    }

    /**
     * 根据code获取详情
     * @param $orderCode
     * @return array|bool|null|\yii\db\ActiveRecord
     */
    public function getDetailByCode($orderCode)
    {
        if (empty($orderCode)) {
            return $this->setAndReturn(-1, "order code 必填");
        }
        //获取order
        $order = $this->_outStockOrderRepository->getDetailByCode($orderCode);
        if (empty($order)) {
            return $this->setAndReturn(-1, "没有该order信息");
        }

        //获取产品
        $products = $this->_outStockProductRepository->getProductsByOrderId($order["id"]);
        $order["products"] = $products;
        return $order;
    }

    /**
     * 租户添加完成
     * @param $orgId
     * @param $orderCode
     * @param $orgName
     * @param $orgCode
     * @param $password
     * @param $operatorId
     * @return bool
     */
    public function addOrg($orgId, $orderCode, $orgName, $orgCode, $password, $operatorId = null)
    {
        $order = MyscrmOutStockOrderEntity::findOne(["order_code" => $orderCode]);
        if (empty($order)) {
            return $this->setAndReturn(-1, "该单号不存在");
        }

        //一个单号关联一个租户开通
        if (!empty($order->org_code)) {
            return $this->setAndReturn(-1, "该单号已经被关联过了");
        }

        $outStockFlowService = $this->getOutStockFlowService($order, $operatorId);

        return $outStockFlowService->actionKT($orgName, $orgId, $orgCode, $password);
    }

    /**
     *  授权添加完之后的操作
     * @param $orderCode
     * @param $contractCode
     * @param $operatorId
     * @param $beginOn
     * @param $endOn
     * @return bool
     */
    public function addAuthContract($orderCode, $contractCode, $operatorId, $beginOn, $endOn)
    {
        $order = MyscrmOutStockOrderEntity::findOne(["order_code" => $orderCode]);
        if (empty($order)) {
            return $this->setAndReturn(-1, "该单号不存在");
        }

        $outStockFlowService = $this->getOutStockFlowService($order, $operatorId);
        //发起授权
        $ret = $outStockFlowService->actionSQ($beginOn, $endOn);
        if (false === $ret) {
            return $this->setAndReturn(-1, "发起授权失败:" . self::getErrMsg());
        }

        //判断是否需要新增草稿合同 ,如果是联营的则需要添加草稿合同
        if ($order->business_pattern == 2) {
            $contract = [];
            $contract["order_code"] = $order->order_code;

            //根据合同签约人的BUCode 和 客户的CstShortCode 生成合同号
            if (empty($order->customer_id)) {
                return $this->setAndReturn(-1, "无法新增草稿合同,未选择客户信息");
            }
            if (empty($order->sign_people_id)) {
                return $this->setAndReturn(-1, "无法新增草稿合同,未选择合同签约人");
            }
            $userInfo = ErpUserRepository::getUserInfoById($order->sign_people_id);
            if (empty($userInfo["BUCode"])) {
                return $this->setAndReturn(-1, "无法新增草稿合同,无法获取BUCode");
            }

            /* @var $contractService ContractService */
            $contractService = \Yii::createObject(ContractService::className());

            $contract["contract_code"] = $contractService->getContractFlowCode($userInfo["BUCode"], $order->customer_code, "");
            $contract["sign_people_id"] = $order->sign_people_id;

            $contract['area_id'] = $userInfo['BUGUID'];
            $contract['area_name'] = $userInfo['CompanyName'];
            $contract['area_code'] = $userInfo['BUCode'];
            $contract['sign_people_department_by'] = $userInfo['DepartmentGUID'];
            $contract['sign_people_department_name'] = $userInfo['DepartmentName'];
            $contract["sign_people_name"] = $userInfo["UserName"];
            $contract["sign_people_abu_name"] = $userInfo["AbuName"];

            $contract["customer_id"] = $order->customer_id;
            $contract["top_customer_name"] = $order->top_customer_name;
            $contract["customer_full_name"] = $order->customer_full_name;
            $contract["customer_name"] = $order->customer_name;
            $contract["customer_code"] = $order->customer_code;

            $contract['contract_property_id'] = '7f8422d0-fce8-11e4-bed8-00155d02c832';//故默认为“云客签约-联营区域”
            $contract['category_id'] = 'b011f523-fcf2-11e4-bed8-00155d02c832';//故默认为“云客租用服务合同”
            $contract['big_category_id'] = '2ae79470-fcf3-11e4-bed8-00155d02c832';//故默认为“服务合同”
            $contract['littler_category_id'] = '62f81bf4-fcf4-11e4-bed8-00155d02c832';//故默认为“软件租用服务”
            $contract['company_id'] = '593d3902-006a-11e5-bed8-00155d02c832';//故默认为“明源云客”

            $contract["attribute_name"] = "false,false,false,false";

            //添加产品
            $productArr = [];
            $products = $this->_outStockProductRepository->getProductsByOrderId($order->id);
            /* @var $contractApplicationService MyscrmContractApplicationService */
            $contractApplicationService = \Yii::createObject(MyscrmContractApplicationService::className());
            foreach ($products as $product) {
                if ($product["apply_num"] == 0) {
                    continue;
                }
                $item = $contractApplicationService->parseContractApplication($product);
                $item['__type'] = "add";
                $item['is_standard'] = 1;
                array_push($productArr, $item);
            }
            $contractId = $contractService->addContract($contract, $productArr, [], false);
            if (false === $contractId) {
                return $this->setAndReturn(-1, "添加草稿合同失败");
            }

            //如果有文档则上传文档
            /* @var $attachmentRepository OutStockAttachmentRepository */
            $attachmentRepository = \Yii::createObject(OutStockAttachmentRepository::className());
            $attachments = $attachmentRepository->getAttachmentsByOrderId($order->id);
            foreach ($attachments as $attachment) {
                $documentModel = new DocumentModel();
                $documentModel->business_id = $contractId;
                $documentModel->document_name = $attachment->filename;
                $documentModel->document_path = $attachment->path;
                $arrs = explode(".", $documentModel->document_path);
                if ($arrs > 1) {
                    $documentModel->document_ext_name = $arrs[count($arrs) - 1];
                }
                $documentModel->document_type = 1;
                $documentModel->created_by = $attachment->created_by;
                $documentModel->modified_by = $attachment->created_by;
                $documentModel->created_on = $attachment->created_on;
                $documentModel->modified_on = $attachment->created_on;
                DocumentRepository::addDocument($documentModel);
            }
        }

        return true;
    }

    /**
     * 获取OutStockFlowService
     * @param $order
     * @param null $userguid
     * @return OutStockFlowService
     * @throws \yii\base\InvalidConfigException
     */
    private function getOutStockFlowService($order, $userguid = null)
    {
        $username = "";
        $departmentGuid = "";
        //外部传的userguid,通常来自接口
        if (!empty($userguid)) {
            $user = ErpUserRepository::getUserById($userguid);
            if (!empty($user)) {
                $username = $user->UserName;
                $departmentGuid = $user->DepartmentGUID;
            }
        } else {
            $userguid = \Yii::$app->user->identity->userguid;
            $username = \Yii::$app->user->identity->username;
            $departmentGuid = \Yii::$app->user->identity->departmentGuid;
        }

        /* @var $operatorModel OperatorModel */
        $operatorModel = \Yii::createObject(OperatorModel::className());
        $operatorModel->user_id = $userguid;
        $operatorModel->username = $username;
        $operatorModel->department_id = $departmentGuid;
        $operator = $operatorModel;

        /* @var $outStockFlowService OutStockFlowService */
        $outStockFlowService = \Yii::createObject([
            'class' => OutStockFlowService::className(),
            'order' => $order,
            'operator' => $operator,
        ]);
        return $outStockFlowService;
    }
}